﻿using ManagementApi.Services.Authentication;
using Modules.System.Dept;
using Modules.System.User;
using PmSoft;
using PmSoft.ApplicationContext;
using PmSoft.Entity;

namespace ManagementApi.Mvc
{
    public class CurrentUserStateProvider : IApplicationContextStateProvider
    {
        private readonly IHttpContextAccessor _httpContextAccessor;

        public CurrentUserStateProvider(IHttpContextAccessor httpContextAccessor)
        {
            _httpContextAccessor = httpContextAccessor;
        }

        public string Name => "CurrentUser";

        IUser? _currentUser;

        public Func<ApplicationContext, T?> Get<T>()
        {
            return context =>
            {
                if (_currentUser != null)
                {
                    return (T)_currentUser;
                }

                var authenticationService = _httpContextAccessor.GetService<UserAuthenticationService>();
                if (authenticationService == null)
                    throw new ArgumentNullException(nameof(authenticationService));

                _currentUser = authenticationService.GetLoginUser();
                if (_currentUser != null && _currentUser.Type == UserType.SysUser && _currentUser is SysUser sysUser && sysUser.DeptId.HasValue && sysUser.DeptId.Value > 0)
                {
                    var deptService = _httpContextAccessor.GetService<DeptService>();
                    if (deptService == null)
                        throw new ArgumentNullException(nameof(deptService));
                    var dept = deptService.GetSysDept(sysUser.DeptId.Value);
                    if (dept == null)
                        throw new ArgumentNullException(nameof(dept));

                    _currentUser = sysUser.AsDeptUser(dept);
                }
                return (T?)_currentUser;

            };
        }
    }
}
